/** js admin file */

$(document).ready(function() {
    
    var idMember;
    var idProject;
    
    var columnCsv = "";
    var columnName = "";
    var columnToDelete = "";
    
    $("#admin-tab").tabs({
        selected: 0
    });
    
    
    
    /*****  ADMIN USER  *******/
    
    var dataTableUsers = $('#dataTableUsers').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "sScrollX": "100%",
        "iDisplayLength":10,
        "bLengthChange": false,
        "sScrollXInner": "110%",
        "bScrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "Afficher _MENU_ membres par page",
            "sZeroRecords": "Aucun utilisateur ne correspond \340 la recherche",
            "sInfo": "Afficher les membres _START_ \340 _END_ sur _TOTAL_ membres",
            "sInfoEmpty": "Afficher 0 \340 0 sur 0 utilisateur",
            "sInfoFiltered": "(filtered from _MAX_ total records)",
            "sSearch": "Recherche",
            "sPrevious":"Precedent"
        },
        "fnDrawCallback": function( oSettings ) {
            addRows(this, 10, 10);        
        }
    });
    
    var dataTableProject = $('#dataTableProjects').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bLengthChange": false,
        "oLanguage": {
            "sLengthMenu": "Afficher _MENU_ projets par page",
            "sZeroRecords": "Aucun projet ne correspond \340 la recherche",
            "sInfo": "Afficher les projets _START_ \340 _END_ sur _TOTAL_ projets",
            "sInfoEmpty": "Afficher 0 \340 0 sur 0 projet",
            "sInfoFiltered": "(filtered from _MAX_ total records)",
            "sSearch": "Recherche",
            "sPrevious":"Precedent"
        },
        "fnDrawCallback": function( oSettings ) {
            addRows(this, 3, 10);
        }
    });
    
    $('#dataTableUsers tr').live('click', function() {
        if ( $(this).hasClass('row_selected') ) {
            $(this).removeClass('row_selected');
            
            $("#user-update").addClass("DTTT_disabled");
            $("#user-delete").addClass("DTTT_disabled");
            $("#user-update").attr("disabled", "disabled");
            $("#user-delete").attr("disabled", "disabled");
            
        }
        else {
            dataTableUsers.$('tr.row_selected').removeClass('row_selected');
            $(this).addClass('row_selected');
            idMember = $(this).attr("id");
            idMember = idMember.split("-");
            
            $("#user-update").removeClass("DTTT_disabled");
            $("#user-delete").removeClass("DTTT_disabled");
            $("#user-update").removeAttr("disabled");
            $("#user-delete").removeAttr("disabled");
        }
    } );
    
    var dialogCreateUser = {
        title: "Utilisateur ",
        modal: true,
        autoOpen: false,
        position: ["center", 100],
        buttons: {
            "Valider": function(){

                if(validateLogin("form-login", "login-info") && validatePassword("form-password","form-password-confirm","password-info", false) && validateEmail("form-email", "mail-info")){
                    //alert("formulaire ok");
                    var dataString = 'form-login='+ $("#form-login").val() + '&form-password=' + $("#form-password").val() + '&form-email=' + $("#form-email").val() + '&form-first-name=' + $("#form-first-name").val() + '&form-last-name=' + $("#form-last-name").val() + '&form-address=' + $("#form-address").val() + '&form-company=' + $("#form-company").val() + '&form-city=' + $("#form-city").val() + '&form-phone=' + $("#form-phone").val() + '&form-zip=' + $("#form-zip").val() + '&form-status=' + $("#form-status").val() + '&form-enabled=' + !$("#form-enabled").is(':checked');  
                    //alert(dataString);
                    $.ajax({
                        type: "POST",
                        url: "main.php?page=1&action=saveUser",
                        data: dataString,
                        success: function(html){

                            alert("Utilisateur ajout\351 avec succ\350s");
                            $("#user-dialog").dialog("close");
                            location.reload();
                        },
                        error: function(){
                            alert("Une erreur est survenue lors de la création de l'utilisateur");
                        }
                    }); 
                }
                else{
                //alert("formulaire incorrect");
                }
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 750
    };
    
    var dialogUpdateUser = {
        title: "Utilisateur : ",
        modal: true,
        autoOpen: false,
        position: ["center", 100],
        buttons: {
            "Valider": function(){
                
                if(validatePassword("form-update-password","form-update-password-confirm","password-update-info", true) && validateEmail("form-update-email", "mail-update-info")){
                    var dataString = 'idMember='+idMember[1] + '&form-update-login='+ $("#form-update-login").val() + '&form-update-password=' + $("#form-update-password").val() + '&form-update-email=' + $("#form-update-email").val() + '&form-update-first-name=' + $("#form-update-first-name").val() + '&form-update-last-name=' + $("#form-update-last-name").val() + '&form-update-address=' + $("#form-update-address").val() + '&form-update-company=' + $("#form-update-company").val() + '&form-update-city=' + $("#form-update-city").val() + '&form-update-phone=' + $("#form-update-phone").val() + '&form-update-zip=' + $("#form-update-zip").val() + '&form-update-status=' + $("#form-update-status").val() + '&form-update-enabled=' + !$("#form-update-enabled").is(':checked');  
                    //alert(dataString);
                    $.ajax({
                        type: "POST",
                        url: "main.php?page=1&action=updateUser",
                        data: dataString,
                        success: function(html){

                            alert("Utilisateur modifi\351 avec succ\350s");
                            $("#user-dialog-update").dialog("close");
                            location.reload();
                        },
                        error: function(){
                            alert("Utilisateur non modifi\351.");
                        }
                    });
                }
                else{
                }

                    
                
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 830,
        open: function(){
            $("#user-dialog-update").load("application/views/AdminDialog.php?idMember="+idMember[1]);
        }
    };
    
    var dialogDeleteUser = {
        title: "Demande de confirmation ",
        modal: true,
        autoOpen: false,
        buttons: {
            "Valider": function(){
                dataString = "idMember="+idMember[1];
                $.ajax({
                    type: "POST",
                    url: "main.php?page=1&action=deleteUser",
                    data: dataString,
                    success: function(html){
                        alert("Utilisateur effac\351 avec succ\350s");
                        $("#user-dialog-delete").dialog("close");
                        location.reload();
                    },
                    error: function(){
                        alert("Une erreur est survenue de la suppression de l'utilisateur");
                    }
                });
                    
                
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 550
    };
        
    $("#user-dialog").dialog(dialogCreateUser);
    $("#user-dialog-delete").dialog(dialogDeleteUser);
    $("#user-dialog-update").dialog(dialogUpdateUser);
    
    $("#user-add").click(function(){
        $("#user-dialog").dialog("open");
    });
    
    $("#user-update").click(function(){
        $("#user-dialog-update").dialog("open");
    });
    
    $("#user-delete").click(function(){
        $("#user-dialog-delete").dialog("open");
    });
    
    function validateLogin(col1, col2){
        //if it's NOT valid  
        if($("#"+col1).val().length < 4){  
            
            $("#"+col1).addClass("ui-state-error");  
            $("#"+col2).html("Veuillez saisir un login.");   
            return false;  
        }  
        //if it's valid  
        else{  
            
            var isValid = false;
            var userName = "checkUser="+$("#"+col1).val(); 
            console.debug("checkUser : "+userName);
            $.ajax({
                type: "GET",
                //dataType: 'json',
                url: "Ajax.php",
                data: userName,
                async: false,
                success: function(response, status, xhr){
                
                    if(response == 1){  
                        //show that the username is available  
                        console.debug("valid : "+ isValid) ;      
                        console.debug("available");
                        isValid =  true;
                        console.debug("valid : "+ isValid) ;   
                        $("#"+col1).removeClass("ui-state-error");  
                        $("#"+col2).html("Ce login disponible.");  
                    }else{  
                        //show that the username is NOT available  
                        console.debug("not available");
                        $("#"+col1).addClass("ui-state-error");  
                        $("#"+col2).html("Ce login n'est pas disponible.");

                    }
                },
                error: function(){

                }
            });
            console.debug("valid final: "+ isValid) ;      
            return isValid;  
        }
        
    }
    
    function validatePassword(idInput, idInputConfirm, idSpan, changePassword){
        //if it's NOT valid  
        //alert("mdp : " + $("#form-password").val() + " confirm : " + $("#form-password-confirm").val());
        
        if(changePassword && ($("#"+idInput).val() == ""))
            return true;
        
        if(($("#"+idInput).val() == "")) {
            $("#"+idInput).addClass("ui-state-error");
            $("#"+idInputConfirm).addClass("ui-state-error");  
            $("#"+idSpan).html("Veuillez saisir un mot de passe.");
            return false;
        }
        //if it's valid  
        else{
            
            if( $("#"+idInput).val() != $("#"+idInputConfirm).val()){
                //alert("false");
                $("#"+idInput).addClass("ui-state-error");
                $("#"+idInputConfirm).addClass("ui-state-error");  
                $("#"+idSpan).html("Les mots de passes ne correspondent pas.");   
                return false;  
            }
            else{
                //alert("true");
                $("#"+idInput).removeClass("ui-state-error");
                $("#"+idInputConfirm).removeClass("ui-state-error");  
                $("#"+idSpan).html("Les mots de passes sont ok.");  
                return true;  
            }
            
        } 
    }
    
    
    function validateEmail(idInput, idSpan){
        //if it's NOT valid
        var regexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
        //checkRegexp( email, , "eg. wsk@ateliers-laumonier.fr" );
        
        if(!(regexp.test($("#"+idInput).val()))){
            $("#"+idInput).addClass("ui-state-error");  
            $("#"+idSpan).html("L'adresse email n'est pas valide.");   
            return false;  
        }
        //if it's valid  
        else{  
            
            $("#"+idInput).removeClass("ui-state-error");  
            $("#"+idSpan).html("Email valide");  
            return true;  
        }  
    }
    
    
    
    /***** END ADMIN USER ******/
    
    
    
    /*****  ADMIN PROJECT  *******/
    
    

    var dialogOptsProject = {
        title: "Projets ",
        modal: true,
        autoOpen: false,
        position: ["center", 100],
        buttons: {
            "Valider": function(){
                console.debug("debut valider");
                if(validateTable("form-projectname") && validateUsers("form-list-admin-2","form-list-user") && validateProject("form-projectname", "projectname-info"))
                {
                    console.debug("if good");
                    
                    $('#project-column>tbody>tr>td:nth-child(1)').each( function(){
                        if($(this).text() != "")
                            columnCsv += $(this).text() + ";";
                    });
       
                    $('#project-column>tbody>tr>td:nth-child(2)').each( function(){
                        if($(this).text() != "")
                            columnName += $(this).text() + ";";      
                    });
                    console.debug("csv " + columnCsv);
                    console.debug("name " + columnName);
                    
                    var dataString = 'form-projectnblign='+ $("#form-projectnblign").val() +'&form-projectname='+ $("#form-projectname").val() + '&form-projectadmin=' + $("#form-list-admin-2").val() + '&form-projectuser=' + $("#form-list-user").val() + '&form-projectgraphe=' + $("#form-default-graphe").val() + '&form-projectcolumn=' + columnCsv + '&form-projectcolumnname=' + columnName;
                    console.debug("dataString " + dataString);
                    $.ajax({
                        type: "POST",
                        url: "main.php?page=1&action=saveProject",
                        data: dataString,
                        success: function(html){

                            alert("Projet cr\351\351");
                            $("#project-dialog").dialog("close");
                            location.reload();
                        },
                        error: function(){
                            alert("Une erreur est survenue lors de la création du projet");
                        }
                    }); 
                    var testIMG = loadIMGProject($('#checkin_pic'));

                }
                else
                    console.debug("no good");
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 800,
        height: 650,
        open: function() {
        //display correct dialog content
        //$("#book-dialog").load("/WSK_PORTAL/application/views/AdminUserDialog.php?user="+id);
        //$("#book-dialog").load("/WSK_PORTAL/application/views/AdminUserDialog.php");
        }
    };
    
    var dialogUpdateProject = {
        title: "Projet : ",
        modal: true,
        autoOpen: false,
        position: ["center", 100],
        buttons: {
            "Valider": function(){
                if(validateTable("form-update-projectname") && validateUsers("form-update-list-admin-2","form-update-list-user"))
                {
                    
                    $('#project-update-column>tbody>tr>td:nth-child(1)').each( function(){
                        if($(this).text() != "")
                            columnCsv += $(this).text() + ";";
                    });
       
                    $('#project-update-column>tbody>tr>td:nth-child(2)').each( function(){
                        if($(this).text() != "")
                            columnName += $(this).text() + ";";      
                    });
                    console.debug("csv " + columnCsv);
                    console.debug("name " + columnName);
                    console.debug("delete " + columnToDelete);
                    
                    var dataString =  'idProject='+idProject[1] + '&form-update-projectname='+ $("#form-update-projectname").val() + '&form-update-projectadmin=' + $("#form-update-list-admin-2").val() + '&form-update-projectuser=' + $("#form-update-list-user").val() + '&form-update-projectgraphe=' + $("#form-update-default-graphe").val()+'&form-update-projectnblign='+ $("#form-update-projectnblign").val() + '&form-update-projectcolumn=' + columnCsv + '&form-update-projectcolumnname=' + columnName + '&form-update-projectcolumndelete=' + columnToDelete;
               
                    
                    $.ajax({
                        type: "POST",
                        url: "main.php?page=1&action=updateProject",
                        data: dataString,
                        success: function(html){

                            alert("Projet modifi\351 avec succ\350s");
                            $("#project-dialog-update").dialog("close");
                            location.reload();
                        },
                        error: function(){
                            alert("Une erreur est survenue lors de la modification du projet");
                        }
                    });
                    var testIMG = loadIMGProject($('#checkin_picUpdate'));
                }
                
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 800,
        height: 450,
        open: function(){
            
            $("#project-dialog-update").load("application/views/AdminDialog.php?idProject="+idProject[1]);
        }
    };
    
    var dialogDeleteProject = {
        title: "Demande de confirmation ",
        modal: true,
        autoOpen: false,
        buttons: {
            "Valider": function(){
                dataString = "idProject="+idProject[1];
                $.ajax({
                    type: "POST",
                    url: "main.php?page=1&action=deleteProject",
                    data: dataString,
                    success: function(html){
                        alert("Projet effac\351 avec succ\350s");
                        $("#project-dialog-delete").dialog("close");
                        location.reload();
                    },
                    error: function(){
                        alert("Une erreur est survenue suppression du projet");
                    }
                });
                    
                
            },
            "Annuler": function(){
                $(this).dialog("close");
            }
                
        },
        width: 550
    };
        
    
     

    
    $('#dataTableProjects tr').live('click',  function() {
        //alert("selected");
        if ( $(this).hasClass('row_selected') ) {
            //alert("has class");
            $(this).removeClass('row_selected');
            
            $("#project-update").addClass("DTTT_disabled");
            $("#project-delete").addClass("DTTT_disabled");
            $("#project-update").attr("disabled", "disabled");
            $("#project-delete").attr("disabled", "disabled");
            
        }
        else {
            //alert("else");
            dataTableProject.$('tr.row_selected').removeClass('row_selected');
            $(this).addClass('row_selected');
            idProject = $(this).attr("id");
            idProject = idProject.split("-");
            //alert(idProject);
            
            $("#project-update").removeClass("DTTT_disabled");
            $("#project-delete").removeClass("DTTT_disabled");
            $("#project-update").removeAttr("disabled");
            $("#project-delete").removeAttr("disabled");
        }
    } );
        
    $("#project-dialog").dialog(dialogOptsProject);
    $("#project-dialog-update").dialog(dialogUpdateProject);
    $("#project-dialog-delete").dialog(dialogDeleteProject);
    
    $("#project-add").click(function(){
        $("#project-dialog").dialog("open");
        
    });
    
    $("#project-update").click(function(){
        $("#project-dialog-update").dialog("open");
    });
    
    $("#project-delete").click(function(){
        $("#project-dialog-delete").dialog("open");
    
    });
    
    $( "#project-add-row" ).button({
        icons: {
            primary: "ui-icon-circle-plus"
        },
        text: false
            
    });
    
    
    
    $( ".project-del-row" ).button({
        icons: {
            primary: "ui-icon-circle-minus"
        },
        text: false
            
    });
    
    $( ".project-update-del-row" ).button({
        icons: {
            primary: "ui-icon-circle-minus"
        },
        text: false
            
    });
    
    $('#project-add-row').live('click',  function() {

        if(validate("column_csv", "column_name")){
            $("#project-column tbody" ).append( "<tr>" +
                "<td>" + $('#column_csv').val() +"</td>" + 
                "<td>" + $('#column_name').val() +"</td>" +
                "<td><button type='button' class='project-del-row'>Supprimer</button></td>" +
                "</tr>" );

            //columnCsv += $("#column_csv").val() + ";";
            //columnName += $("#column_name").val() + ";";

            $("#column_csv").val("");
            $("#column_name").val("");

            $( ".project-del-row" ).button({
                icons: {
                    primary: "ui-icon-circle-minus"
                },
                text: false

            });
        }
        else
            alert("Veuillez saisir les deux colonnes.");
    //alert("csv : "+columnCsv + "\t name :  "+columnName);

    });
    
    $('#project-update-add-row').live('click',  function() {
        console.debug("click on +");
        if(validate("update-column_csv", "update-column_name")){
            $("#project-update-column tbody" ).append( "<tr>" +
                "<td>" + $('#update-column_csv').val() +"</td>" + 
                "<td>" + $('#update-column_name').val() +"</td>" +
                "<td><button type='button' class='project-update-del-row'>Supprimer</button></td>" +
                "</tr>" );

            //columnCsv += $("#column_csv").val() + ";";
            //columnName += $("#column_name").val() + ";";

            $("#update-column_csv").val("");
            $("#update-column_name").val("");

            $( ".project-update-del-row" ).button({
                icons: {
                    primary: "ui-icon-circle-minus"
                },
                text: false

            });
        }
        else
            alert("Veuillez saisir les deux colonnes.");
    //alert("csv : "+columnCsv + "\t name :  "+columnName);

    });
    
    $('.project-del-row').live('click',  function() {
        $(this).closest('tr').remove();
    });
    
    $('.project-update-del-row').live('click',  function() {
        var tr = $(this);
        $( "#delete-confirm" ).dialog({
            title:"Confirmation",
            resizable: false,
            height:200,
            modal: true,
            buttons: {
                "Je confirme": function() {
                    //console.debug("td : "+tr.parent().siblings(":first").text());
                    columnToDelete += tr.parent().siblings(":first").text() + ";";
                    tr.closest('tr').remove();
                    $( this ).dialog( "close" );
                },
                "Annuler": function() {
                    $( this ).dialog( "close" );
                }
            }
        });
        
        
    });
    
    
    function validateTable(col1){
        //if it's NOT valid  
        if($("#"+col1).val().length < 3){  
            $("#"+col1).addClass("ui-state-error");  
            $("#projectname-info").html("3 caractères minimum pour le nom d'un projet");   
            return false;  
        }  
        //if it's valid  
        else{             
            $("#"+col1).removeClass("ui-state-error");  
            // $("#login-info").html("Login ok");  
            return true;  
        }  
    }
    
    function validateUsers(col1, col2){
        //console.debug($("#"+col1).val() + "et : " + $("#"+col2).val())
        //alert($("#"+col1).val() + " et : " + $("#"+col2).val());
        var a = $("#"+col1).val();
        a = String(a);
        var b = $("#"+col2).val();
        b = String(b);
        var m = null;
        var n = null;
        
        if(a != null){
            //console.debug("not null");
            if(a.length > 1){
                //console.debug("sup à 1");
                m = a.split(',');
                //console.debug(m);
            }
            if(b.length > 1){
                //console.debug("sup à 1");
                n = b.split(',');
                //console.debug(n);
            }
            
        }
        else{
            //console.debug("null");
        }
        //if it's NOT valid 
        //console.debug($("#form-list-admin-2").val());
        if($("#"+col1).val() == null || $("#"+col2).val() == null){  
            alert("Vous devez sélectionner au moins un utilisateur et un modérateur");  
            return false;  
        }  
        //if it's valid  
        else if (a == b){
            alert("Veuillez ne pas sélectionner de modérateur identique à l'utilisateur.");
            return false;
        }
        else if (n != null){
            if ($.inArray(a, n) != -1){
                //console.debug("array n" + a + " et n : "+n);
                alert("Un des modérateurs est identique à un utilisateur");
                return false;
            }
            else
                return true;
        }
        else if(m != null){
            if ($.inArray(b, m) != -1){
                alert("Un des utilisateurs est identique à un modérateur");
                return false;
            }
            else
                return true;
        }
        else{             
                        
            // $("#login-info").html("Login ok");  
            return true;  
        }  
    }
    
    function validateProject(col1, col2){
        var isValid = false;
        var projectName = "checkProject="+$("#"+col1).val(); 
        console.debug("checkProject : "+projectName);
        $.ajax({
            type: "GET",
            //dataType: 'json',
            url: "Ajax.php",
            data: projectName,
            async: false,
            success: function(response, status, xhr){
                
                if(response == 1){  
                    //show that the username is available  
                    console.debug("valid : "+ isValid) ;      
                    console.debug("available");
                    isValid =  true;
                    console.debug("valid : "+ isValid) ;   
                    $("#"+col1).removeClass("ui-state-error");  
                    $("#"+col2).html("Nom de projet disponible.");  
                }else{  
                    //show that the username is NOT available  
                    console.debug("not available");
                    $("#"+col1).addClass("ui-state-error");  
                    $("#"+col2).html("Le nom de projet n'est pas disponible.");

                }
            },
            error: function(){

            }
        });
        console.debug("valid final: "+ isValid) ;      
        return isValid;
    }
    
    
    
    
    function validate(col1, col2){
        //if it's NOT valid  
        if(($("#"+col1).val() == "") || ($("#"+col2).val() == "")){  
            $("#"+col1).addClass("ui-state-error");  
            $("#"+col2).addClass("ui-state-error");  
            return false;  
        }  
        //if it's valid  
        else{             
            $("#"+col1).removeClass("ui-state-error");  
            $("#"+col2).removeClass("ui-state-error");  
            return true;  
        }  
    }
    $('#form-list-admin-2').multiselect({
        minWidth: 160,
        checkAllText: 'tout cocher',
        uncheckAllText: 'tout d&eacute;cocher',
        noneSelectedText: 'Modérateur(s) :',
        selectedText: "# Modérateur(s)"
    });
    $('#form-list-user').multiselect({
        minWidth: 160,
        checkAllText: 'tout cocher',
        uncheckAllText: 'tout d&eacute;cocher',
        noneSelectedText: 'Utilisateurs :',
        selectedText: "# Utilisateurs(s)"
    });
    
    
    
    $('#form-update-list-user').multiselect({
        minWidth: 160,
        checkAllText: 'tout cocher',
        uncheckAllText: 'tout d&eacute;cocher',
        noneSelectedText: 'Utilisateurs :',
        selectedText: '# Utilisateurs(s)'
    });
    
    $(".chzn-select").chosen();
    $(".chzn-select-deselect").chosen({
        allow_single_deselect:true
    });
    
    function progressHandlingFunction(e){
        if(e.lengthComputable){
            $('progress').attr({
                value:e.loaded,
                max:e.total
                });
        }
    }
    
    /* fcmcAddrows is a utility function called from within <a href="/ref#fnDrawCallback">fnDrawCallback</a>  * obj is the jQuery table object, numberColumns is result of _fnVisbleColumns,
 * and targetRows is the total number of visible rows we need.
 */
 
    function addRows(obj, numberColumns, targetRows) {
        var tableRows = obj.find('tbody tr'); // grab the existing data rows
        var numberNeeded = targetRows - tableRows.length; // how many blank rows are needed to fill up to targetRows
        var lastRow = tableRows.last(); // cache the last data row
        var lastRowCells = lastRow.children('td'); // how many visible columns are there?
        var cellString;
        var highlightColumn;
        var rowClass;
 
        // The first row to be added actually ends up being the last row of the table.
        // Check to see if it should be odd or even.
        if (targetRows%2) {
            rowClass= "odd";
        } else {
            rowClass = "even"; //
        }
 
        // We only sort on 1 column, so let's find it based on its classname
        lastRowCells.each(function(index) {
            if ($(this).hasClass('sorting_1')) {
                highlightColumn = index;
            }
        });
 
        /* Iterate through the number of blank rows needed, building a string that will
   * be used for the HTML of each row. Another iterator inside creates the desired
   * number of columns, adding the sorting class to the appropriate TD.
   */
        for (i=0;i<numberNeeded;i++) {
            cellString = "";
            for (j=0;j<numberColumns;j++) {
                if (j == highlightColumn) {
                    cellString += '<td class="sorting_1">&nbsp;</td>';
                } else {
                    cellString += '<td>&nbsp;</td>';
                }
            }
 
            // Add the TR and its contents to the DOM, then toggle the even/odd class
            // in preparation for the next.
            lastRow.after('<tr class="'+rowClass+'">'+cellString+'</tr>');
            rowClass = (rowClass == "even") ? "odd" : "even";
        }
    }
    $('#bpci-polaroid-upload').click( function(){
    	   
        var file = $('#checkin_pic').get(0).files[0];
        var max_file_size = 2;//size in MO
    	   
        /* check file type, we only want images */
        if( file.type.indexOf('image') == -1 ) {
            // alert('Please select an image file only.');
            return false;
        }   

        name = file.name;
        size = file.size / 1024;
        type = file.type;
    	   
        sizeInMo = Math.round((size / 1024) * 100) / 100 ;
    	   
        /* check file size */
        if( sizeInMo > max_file_size ){
            // alert('Your image is too big, please reduce it (max file size : ' + max_file_size + 'MO)')
            return false;
        }
    	   
        var reader = new FileReader();
    	   
        $('#bpci-polaroid-upload').addClass('bpci-loading');
    	   
        reader.onload = (function(theFile) {
            return function(e) {
                bpciImageUpload(e.target.result, type, name);
                return false;
            };
        })(file);

        reader.readAsDataURL(file);
    	   
        return false;
    });
    function loadIMGProject(ficher)
    {
        var file = ficher.get(0).files[0];
        //var file = $('#checkin_picUpdate').get(0).files[0];
        var max_file_size = 2;// en MO
      
        name = file.name;
        size = file.size / 1024;
        type = file.type;
       	   
        sizeInMo = Math.round((size / 1024) * 100) / 100 ;
        if( sizeInMo > max_file_size ){
            alert('Image trop grande 2 MO maximum')
            return false;
        }             	   
        var reader = new FileReader();         	   
        $('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover').addClass('bpci-loading'); 
        reader.onload = (function(theFile) {
            return function(e) {
                bpciImageUpload(e.target.result, type, name);
                return false;
            };
        })(file);

        reader.readAsDataURL(file);
       	   
        return false;
    }
    function bpciImageUpload( img, type, name ) {
        /*
    	   * ajaxurl is already defined in BuddyPress
    	   * if you're not using BuddyPress, you can define it this way :
    	   * ajaxurl = "<?php echo admin_url('admin-ajax.php');?>";
    	   */
    	   
        $.post( "main.php?page=1&action=uploadImg", {
            action: 'upload_checkin_pic',
            /*'_wpnonce_post_checkin': $("input#_wpnonce_post_checkin").val(), //security in bp-checkins */
            'encodedimg': img,
            'imgtype':type,
            'imgname':name
        },
        function(response) {
    	      
            if( response[0] != "0" ) {
                sendToContentEditable( response[1], response[2]);
            }
            else alert(response[1]);
        }, 'json');
    	         
    }

    function sendToContentEditable(fullimage, resizedimage) {
    	   
        alert('full image url: '+fullimage+' / thumbnail url: '+ resizedimage);
    	   
    }
});